package com.nettest.action.system;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.nettest.action.BaseJsonAction;
import com.nettest.bean.system.StaffCriteriaVo;
import com.nettest.entity.system.Department;
import com.nettest.entity.system.Role;
import com.nettest.entity.system.Staff;
import com.nettest.service.event.LoginUserCreatedEvent;
import com.nettest.service.system.DeptService;
import com.nettest.service.system.StaffService;
import com.nettest.util.StringUtils;
import com.opensymphony.xwork2.validator.ValidationException;

@Namespace("/system/user")
@Action("userManage")
@Results({@Result(name = "success", location = "/system/userManage.jsp") })
public class UserManageAction extends BaseJsonAction implements ApplicationContextAware{

	private static final long serialVersionUID = 7796054923782630546L;
	private StaffCriteriaVo criteria;

	private List<Staff> staffInfoList;
	private String ids;
	private String operate;
	@Autowired
	private StaffService staffService;
	@Autowired
	private DeptService deptService;
	private Staff staff;
	@Autowired
	private PasswordEncoder passwordEncoder;
    private ApplicationContext applicationContext;

    @Action(value = "list",results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria,staffService,deptService"}) })
    public String list() throws Exception {
		int intPage = getPage();
		int intRows = getRows();
			
		criteria.setPageSize(intRows);
		criteria.setPageNo(intPage);
		criteria.setSortField(getSort());
		criteria.setDescOrAsc(getOrder());
		try {
			staffInfoList = staffService.queryByCriteria(criteria);
			setTotal(staffService.totalSize(criteria));
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	public UserManageAction() {
		super();
	}

	@Action(value = "save", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria" }) })
	public String save() throws Exception{
		try {
			if (staff != null) {
	            Staff oldStaff = staffService.getOneStaff(staff.getStaffNo());
	            if (oldStaff != null) {
	                if ("insert".equalsIgnoreCase(operate)) {
	                    throw new ValidationException(new StringBuilder("账号'")
	                            .append(staff.getStaffNo()).append("'已经被占用！")
	                            .toString());
	                }
	                
	                staffService.updateStaff(staff,oldStaff);
	            }
	            else {
	            	staff = staffService.insertStaff(staff);
	            	applicationContext.publishEvent(new LoginUserCreatedEvent(this, staff, staff.getPassword()));
	            }
	        }
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			e.printStackTrace();
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	@Action(value = "edit", results = { @Result(name = "success", location = "/system/staffEdit.jsp")})
	public String edit() throws Exception{
		if (!StringUtils.isBlank(staff.getStaffNo())) {
            staff = staffService.getOneStaff(staff.getStaffNo());
            if (staff != null && !StringUtils.isBlank(staff.getDeptId())) {
                Department dept = deptService.queryDeptById(staff.getDeptId());
                if (dept != null) {
                    staff.setDeptName(dept.getDeptName());
                }
            }
            
            if (staff != null && !staff.getRoles().isEmpty()) {
                StringBuilder roleNames = new StringBuilder();
                StringBuilder roleIds = new StringBuilder();
                for (Role role : staff.getRoles()) {
                	roleNames.append(role.getRoleName()).append(";");
                	roleIds.append(role.getRoleId()).append(";");
				}
                roleNames.deleteCharAt(roleNames.length() - 1);
                roleIds.deleteCharAt(roleIds.length() - 1);
                staff.setRoleName(roleNames.toString());
                staff.setRoleId(roleIds.toString());
            }
        }
		return SUCCESS;
	}
	@Action(value = "delete", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria,data,list" }) })
	public String delete() throws Exception {
		try {
			if(ids != null) {
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					staffService.delete(Long.valueOf(split[i]));
				}
			}
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			e.printStackTrace();
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	public void validateSave() {
		
	}
	
	@JSON(name="rows")
	public List<Staff> getLists(){
		return this.staffInfoList;
	}
	
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public StaffCriteriaVo getCriteria() {
		return criteria;
	}

	public void setCriteria(StaffCriteriaVo criteria) {
		this.criteria = criteria;
	}

	public String getOperate() {
		return operate;
	}

	public void setOperate(String operate) {
		this.operate = operate;
	}

	public Staff getStaff() {
		return staff;
	}

	public void setStaff(Staff staff) {
		this.staff = staff;
	}
}